package com.zcz.authentication.config;

import com.zcz.authentication.bean.Perms;
import com.zcz.authentication.bean.User;
import com.zcz.authentication.mapper.PermsMapper;
import com.zcz.authentication.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/**
 * 自定义realm
 * @author Administrator
 *
 */
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	@Autowired
	private PermsMapper permsMapper;
	/**
	 * 执行授权逻辑
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.err.println(" 执行授权逻辑");

		//给资源进行授权
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//添加 资源授权字符串
		//获取当前登录用户
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		List<Perms> list = permsMapper.list(user.getId());
		//多个权限就把几个遍历出来添加
		for (Perms perms : list) {
			info.addStringPermission(perms.getQuanxian());
		}
		return info;
	}
	/**
	 * 执行认证逻辑
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken argo) throws AuthenticationException {
		System.err.println("执行认证逻辑");
		
		//编写shiro判断逻辑，判断用户名和密码
		//判断用户名
		UsernamePasswordToken token=(UsernamePasswordToken)argo;
		System.err.println(token+"****************");
		//数据库的用户名和密码
		User user = userService.findByName(token.getUsername(), null);
		if (user == null) {
			//用户名不存在
			return null;
		}
		return new SimpleAuthenticationInfo(user,user.getPassword(),"");
		
	}
	
	//清除缓存
	public void claerCached() {
		PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principalCollection);
	}


}
